package com.itheima.tliasmanagementspringboot.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.tliasmanagementspringboot.common.R;
import com.itheima.tliasmanagementspringboot.utils.JwtUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;

/**
 * 开启DemoFilter过滤器
 */
@WebFilter(urlPatterns = "")
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("拦截方法执行,拦截到请求了....");//拦截到请求时,调用该方法,可调用多次
        //1.获取请求的url(排除login)
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;//向下转型,子类方法更多更强大
        HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
        String requestURL = httpServletRequest.getRequestURI();//不带协议 ip 端口
        StringBuffer requestURL2 = httpServletRequest.getRequestURL();//带协议 ip 端口
        if (requestURL.contains("login")) {
            //放行请求
            filterChain.doFilter(servletRequest, servletResponse);
            return;//一定要加return
        }

        //2.获取token
        String token = httpServletRequest.getHeader("token");
        try {
            //3.解析token
            JwtUtils.parseJWT(token);
            filterChain.doFilter(servletRequest, servletResponse);
            System.out.println("放行后逻辑......");
            return;
        } catch (Exception e) {
            e.printStackTrace();
            //响应code=0 msg=NOT_LOGIN
            R r = R.error("NOT_LOGIN");//jackson,框架自带的对象转换成json格式的 还有第三方的fastjson
            String json = JSON.toJSONString(r);
            httpServletResponse.getWriter().write(json);
            return;
        }

    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
